const { Controller } = require("egg");

const { getReqParams, getResBody, getResList, getPageParams, getReqToken } = require("../../utils");
const validRules = require("../../utils/valid/rules");
const { noteMenus } = require("../../scripts/note/mock");
const { getTablesSelectSql } = require("../../scripts/note/core/creator/mysql/_utils/tablesSelect");

const tableName = "user";
const tables = [
  {
    user: [
      "*",
      // "(SELECT COUNT(*) FROM user_relations WHERE focused_id = user.id) AS fans_num",
      // "(SELECT COUNT(*) FROM user_relations WHERE focus_id = user.id) AS focus_num",
      // "(SELECT COUNT(*) FROM system_notice WHERE accept_id = user.id) AS notice_num",
      // "(SELECT COUNT(*) FROM visitor WHERE visited_id = user.id) AS visitor_num",
    ],
  },
  // {
  //   "note|LEFT JOIN note ON user.id=note.create_id": [
  //     "COUNT(DISTINCT note.id) AS note_num",
  //     // "SUM(DISTINCT note.view_num) AS view_num",
  //     "SUM(DISTINCT note.praise_num) AS praise_num",
  //     "SUM(DISTINCT note.belittle_num) AS belittle_num",
  //     "SUM(DISTINCT note.collect_num) AS collect_num",
  //     "SUM(DISTINCT note.share_num) AS share_num",
  //     "SUM(DISTINCT note.report_num) AS report_num",
  //     "AVG(DISTINCT note.score) AS score",
  //   ],
  // },
];
const filter = {
  // 其他条件，例：笔记未删除、用户未注销等
  // "sn.type|<=": 15,
};
module.exports = class UserController extends Controller {
  // 查详情
  async detail() {
    const { ctx, service } = this;
    const rules = { id: validRules.id };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const data = await service.common.detail(tables, { where: { ...params, ...filter }, group: ["user.id"] }); // "sn.accept_id"
    ctx.body = getResBody({ data });
  }
  // 登录
  async login() {
    const isTemp = true;
    const { ctx, app, service } = this;
    const rules = {
      password: { ...validRules.password, required: true },
      phone: { ...validRules.phone, required: true },
      captcha: { required: !isTemp },
    };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const { phone, password, captcha } = params;
    let errMsg = undefined;
    let data = await service.common.detail(tables, { where: { phone, ...filter } });
    if (!data) errMsg = "不存在该用户";
    else if (password !== data.password) errMsg = "电话号码或密码不正确";
    // else if (captcha.toUpperCase() !== ctx.session.captcha?.toUpperCase()) errMsg = "验证码不正确"; // isTemp
    const token = app.jwt.sign({ phone, password }, app.config.jwt.secret, { expiresIn: `${60 * 60 * 24}s` });
    ctx.cookies.set("token", token, {
      maxAge: 1000 * 3600 * 24 * 7, // cookie存储一天 设置过期时间后关闭浏览器重新打开cookie还存在
      httpOnly: false, // 仅允许服务获取,不允许js获取
      signed: true, // 对cookie进行签名 防止用户修改cookie
      encrypt: false, // 是否对cookie进行加密 如果cookie加密那么获取的时候要对cookie进行解密
    });
    // 当 CSRF token 储存在 Cookie 中时，若在同一浏览器上发生用户切换，则新登录用户将使用旧 token（前一用户的），造成安全风险，故每次用户登录时必须刷新 CSRF token
    ctx.rotateCsrfSecret();
    data = errMsg ? undefined : { token, ...data };
    ctx.session.user = data;
    ctx.body = getResBody({ data, msg: errMsg });
  }
  // 登出
  async logout() {
    const { ctx, service, app } = this;
    const rules = {};
    // const rules = {
    //   password: { ...validRules.password, required: true },
    //   phone: { ...validRules.phone, required: true },
    //   captcha: { required: !isTemp },
    // };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    const token = getReqToken(ctx);
    const info = app.config.jwt;
    const { phone, password } = ctx.app.jwt.verify(token, info.secret);
    const data = await service.common.detail(tableName, { where: { phone, password } });
    const errMsg = data ? undefined : "不存在该用户";
    ctx.body = getResBody({ msg: errMsg });
  }
  // 用户收藏夹
  async collectTree() {
    const { ctx, service, app } = this;
    const rules = {};
    // const rules = {
    //   password: { ...validRules.password, required: true },
    //   phone: { ...validRules.phone, required: true },
    //   captcha: { required: !isTemp },
    // };
    const params = getReqParams(ctx, rules);
    if (!params) return;
    // const token = getReqToken(ctx);
    // const info = app.config.jwt;
    // const { phone, password } = ctx.app.jwt.verify(token, info.secret);
    // const data = await service.common.detail(tableName, { where: { phone, password } });
    // const errMsg = data ? undefined : "不存在该用户";
    // ctx.body = getResBody({ msg: errMsg });
    ctx.body = getResBody({ data: noteMenus });
  }
};
